import React from 'react';
import {Card, message, Table, Input} from 'antd';
import SearchForm from '../../components/AutoForm/SearchForm';
import {connect} from 'dva';
import EditForm from "../../components/AutoForm/EditForm";

const { TextArea } = Input
@connect(({ trackOrder, loading }) => ({
  passLoading: loading.effects['trackOrder/trackPass'],
  rejectLoading: loading.effects['trackOrder/trackReject'],
  tableLoading: loading.effects['trackOrder/page'],
  formLoading: loading.effects['trackOrder/trackPass'],
  tableData: trackOrder.pageList,
  pagination: trackOrder.pagination,
  columns: trackOrder.columns,
  searchFields: trackOrder.searchFields,
  searchValues: trackOrder.searchValues,
  selectionIds: trackOrder.selectionIds,
  selectedRows: trackOrder.selectedRows,
}))
export default class EditableTable extends React.Component {

  state = {
    passTitle: '通过',
    passForm: { },
    passModal: false,
    passRows: [
      {
        cols: [
          {
            label: '备注',
            name: 'remark',
            md: 24,
            component: <TextArea rows={3}/>,
          },
        ],
      },]
  }
  componentDidMount() {
    this.handleSearch();
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'trackOrder/handleSearchChange',
      payload: fields,
    });
  };

  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'trackOrder/page',
      payload: param,
    });
  };


  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'trackOrder/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };

  onSend = () => {
    const { selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行数据');
    }

    let trackOrder = selectedRows[0];
    let title = ''
    if (trackOrder.status === 'COST_AUDIT') {
        title = '通过（成本审核）'
    } else if (trackOrder.status === 'LOAD_IN') {
      title = '通过（货物装车）'
    } else if (trackOrder.status === 'LOAD_OFF') {
      title = '通过（货物送达）'
    } else {
      return message.error('状态异常');
    }



    this.setState({
      passTitle: title,
      passForm: {
        remark: {
          name: 'remark',
          value: trackOrder.remark
        }
      },
      passModal: true
    })
  };

  onPass = field => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行数据');
    }

    let trackOrder = selectedRows[0];
    if (trackOrder.status === 'COST_AUDIT') {
      trackOrder.status = 'LOAD_IN';
    } else if (trackOrder.status === 'LOAD_IN') {
      trackOrder.status = 'LOAD_OFF';
    } else if (trackOrder.status === 'LOAD_OFF') {
      trackOrder.status = 'RECEIPT';
    } else {
      return message.error('状态异常');
    }
    trackOrder.remark = field.remark
    dispatch({
      type: 'trackOrder/trackPass',
      payload: trackOrder,
    }).then(() => {
      this.handlePassVisble()
      this.handleSearch();
    });
  }

  handlePassChange = field => {
    this.setState({
      passForm: field
    })
  }

  handlePassVisble = () => {
    this.setState({
      passModal: false
    })
  }

  onReject = () => {
    const { dispatch, selectedRows } = this.props;
    if (selectedRows.length !== 1) {
      return message.error('请选择一行数据');
    }
    let trackOrder = selectedRows[0];

    if (trackOrder.status === 'LOAD_IN') {
      trackOrder.status = 'COST_AUDIT';
    } else if (trackOrder.status === 'LOAD_OFF') {
      trackOrder.status = 'LOAD_IN';
    } else {
      return message.error('状态异常');
    }

    dispatch({
      type: 'trackOrder/trackReject',
      payload: trackOrder,
    }).then(() => {
      this.handleSearch();
    });
  };

  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch,
      passLoading,
      rejectLoading,
      formLoading
    } = this.props;
    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'trackOrder/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'trackOrder/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange,
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="追踪订单->操作"
          layout="inline"
          onFieldsChange={this.handleSearchChange}
          isReject={true}
          onReject={this.onReject}
          onSend={this.onSend}
          onSubmit={() => {this.handleSearch('btn')}}
          isSend={true}
          passLoading={passLoading}
          rejectLoading={rejectLoading}
          fields={searchFields}
          fieldValue={searchValues}
        />

        <Table
          bordered
          rowKey="id"
          loading={tableLoading}
          dataSource={tableData}
          columns={optColumns}
          rowSelection={rowSelection}
          rowClassName="editable-row"
          scroll={{ x: 'max-content' }}
          size="small"
          pagination={pagination}
          expandedRowRender={this.expandedRowRender}
        />
        <EditForm
          title={this.state.passTitle}
          rows={this.state.passRows}
          fieldValue={this.state.passForm}
          onFieldsChange={this.handlePassChange}
          onCancel={this.handlePassVisble}
          onOk={this.onPass}
          confirmLoading={formLoading}
          visible={this.state.passModal}
        />
      </Card>
    );
  }
}
